/*
 * Copyright (C), 2015-2019
 * FileName: OperandStack
 * Author:   lizhao
 * Date:     2019-02-12 19:43
 * Description: 操作数栈
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.lizhaoblog.jjvm.runtime;

import com.lizhaoblog.jjvm.util.ByteUtil;

/**
 * 〈一句话功能简述〉<br>
 * 〈操作数栈〉
 *
 * @author lizhao
 * @date 2019-02-12 19:43
 * @since 1.0.0
 */
public class OperandStack {
    private int topIndex;
    private Slot[] operands;

    public OperandStack(int size) {
        operands = new Slot[size];
        for (int i = 0; i < size; i++) {
            operands[i] = new Slot();
        }
    }

    public void pushInt(int val) {
        operands[topIndex].num = val;
        topIndex++;
    }

    public int popInt() {
        topIndex--;
        return operands[topIndex].num;
    }

    public void pushRef(JObject val) {
        operands[topIndex].ref = val;
        topIndex++;
    }

    public JObject popRef() {
        topIndex--;
        JObject val = operands[topIndex].ref;
        operands[topIndex].ref = null;
        return val;
    }


    public void pushFloat(float val) {
        operands[topIndex].num = Float.floatToIntBits(val);
        topIndex++;
    }

    public Float popFloat() {
        --topIndex;
        return Float.intBitsToFloat(operands[topIndex].num);
    }

    public void pushLong(long val) {
        int[] ints = ByteUtil.long2IntArr(val);
        operands[topIndex++].num = ints[0];
        operands[topIndex++].num = ints[1];
    }

    public long popLong() {
        topIndex--;
        topIndex--;
        return ByteUtil.int2Long(operands[topIndex].num, operands[topIndex + 1].num);
    }

    public void pushDouble(double val) {
        long res = Double.doubleToLongBits(val);
        pushLong(res);
    }

    public double popDouble() {
        long res = popLong();
        return Double.longBitsToDouble(res);
    }

}
